module.exports = class extends think.kms.admin {
  constructor(ctx) {
    super(ctx);
    this.db = this.model('menu');
    this.tactive = 'setup';
  }

  async indexAction() {
    this.user = await this.session('userInfo');
    const pid = this.get('pid') || 0;
    const draw = this.get('draw');
    if (pid) {
      const data = await this.db.where({id: pid}).find();
    }
    let i = pid;
    const breadcrumb = [];
    while(i != 0) {
      const nav = await this.db.where({id: i}).field('id,title,pid').find();
      breadcrumb.push(nav);
      i = nav.pid;
    }
    const all_menu = await this.db.field('id,title').select();
    const obj = {};
    all_menu.forEach(v => {
      obj[v.id] = v.title;
    });
    
    const map = {};
    map.pid = pid;
    map.status = ['>', '-1']
    const list = await this.db.where(map).order('sort asc ,id asc').select();
    think.logger.debug(list);
    if (list) {
      list.forEach((v, k) => {
        if (v.pid) {
          v.up_title = obj[v.pid];
        } else {
          v.up_title = '一级菜单';
        }
        v.group = (this.config('setup.MENU_GROUP'))[v.group];
      });
    }
    const relist = {
      'draw': draw,
      'data': list,
      'breadcrumb': breadcrumb.reverse()
    };
    this.assign({
      title: '系统菜单管理',
      'alert': {
        title: '操作安全警告',
        content: '谨慎操作，请勿随意修改数据！',
        type: 'danger'
      },
      pid,
      relist: relist
    })
    return this.display();
  }

  /**
     * 添加菜单
     * @returns {*}
     */
  async addAction() {
    if (this.isAjax('post')) {
      const data = this.post();
      data.status = 1;
      const add = await this.db.add(data);
      think.cache('adminenu', null);// 清除菜单缓存
      return this.success('添加成功！');
    } else {
      const menus = arr2table(this.adminmenu);
      const pid = this.get('pid');
      this.assign({
        menus,
        pid
      });
      return this.display();
    }
  }

  async delAction() {
    const id = this.post('id');
    await this.db.where({id}).update({'status': -1})
    return this.success('删除成功');
  }
}